package com.example.blog.modules.article.controller;

import com.example.blog.common.api.ApiResponse;
import com.example.blog.common.security.HasPermission;
import com.example.blog.modules.article.dto.CategoryDTO;
import com.example.blog.modules.article.service.CategoryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "分类管理", description = "分类管理相关接口")
@RestController
@RequestMapping("/api/categories")
@RequiredArgsConstructor
public class CategoryController {

    private final CategoryService categoryService;

    @Operation(summary = "创建分类")
    @PostMapping
    @HasPermission("category:create")
    public ApiResponse<CategoryDTO> createCategory(@Valid @RequestBody CategoryDTO categoryDTO) {
        return ApiResponse.success(categoryService.createCategory(categoryDTO));
    }

    @Operation(summary = "更新分类")
    @PutMapping("/{id}")
    @HasPermission("category:update")
    public ApiResponse<CategoryDTO> updateCategory(@PathVariable Long id, @Valid @RequestBody CategoryDTO categoryDTO) {
        return ApiResponse.success(categoryService.updateCategory(id, categoryDTO));
    }

    @Operation(summary = "删除分类")
    @DeleteMapping("/{id}")
    @HasPermission("category:delete")
    public ApiResponse<Void> deleteCategory(@PathVariable Long id) {
        categoryService.deleteCategory(id);
        return ApiResponse.success();
    }

    @Operation(summary = "获取分类详情")
    @GetMapping("/{id}")
    @HasPermission("category:read")
    public ApiResponse<CategoryDTO> getCategory(@PathVariable Long id) {
        return ApiResponse.success(categoryService.getCategory(id));
    }

    @Operation(summary = "获取所有分类")
    @GetMapping("/all")
    @HasPermission("category:read")
    public ApiResponse<List<CategoryDTO>> getAllCategories() {
        return ApiResponse.success(categoryService.getAllCategories());
    }

    @Operation(summary = "获取分类列表")
    @GetMapping
    @HasPermission("category:read")
    public ApiResponse<Page<CategoryDTO>> getCategories(
            @RequestParam(required = false) String keyword,
            Pageable pageable) {
        return ApiResponse.success(categoryService.getCategories(keyword, pageable));
    }
} 